package db

import (
	"fmt"
	"go-demo/app/config"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

var DB *gorm.DB

func InitMySQL() {
	var err error
	// 自定义日志模板,打印SQL语句
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second, // 慢SQL阀值
			LogLevel:      logger.Info, // 级别
			Colorful:      true,
		},
	)

	DB, err = gorm.Open(mysql.Open(config.GetConfig().Database.DSN), &gorm.Config{
		CreateBatchSize: 1000, // 批量创建时，每批的数量
		Logger:          newLogger,
	})
	if err != nil {
		panic(fmt.Errorf("mysql数据库连接错误:%w", err))
	}
	if DB.Error != nil {
		panic(fmt.Errorf("数据库错误:%w", DB.Error))
	}
}
